import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Card, Badge, Table, Divider, Spin, Row, Col, Button } from 'antd';
import QRCode from 'qrcode.react';
import JsBarcode from 'jsbarcode';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './index.less';

const { Description } = DescriptionList;
const progressColumns = [
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
  }, {
    title: '服务项目',
    dataIndex: 'rate',
    key: 'rate',
  }, {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => (
      text === 'success' ? <Badge status="success" text="成功" /> : <Badge status="processing" text="进行中" />
    ),
  }, {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
  }, {
    title: '结果',
    dataIndex: 'cost',
    key: 'cost',
  },
];

@connect(state => ({
  ...state.assetDetail,
}))
export default class AssetDetail extends Component {
  componentDidMount() {
    const { id } = this.props.match.params;
    const { dispatch } = this.props;
    if (!id) {
      dispatch(routerRedux.push('/404'));
      return;
    }
    dispatch({
      type: 'assetDetail/fetchDetail',
      payload: {
        id,
      },
    });
  }

  componentDidUpdate() {
    const { id } = this.props.match.params;
    // generate barcode
    const barcodeRef = this.barcode;
    if (barcodeRef) {
      JsBarcode(barcodeRef, `${id}${Math.floor(Math.random() * 10000)}`, {
        format: 'codabar',
        lineColor: '#222',
        width: 4,
        height: 40,
        displayValue: false,
      });
    }
  }

  saveCanvas = ({ target }) => {
    const printType = target.dataset.type;
    if (!printType) return;

    // print qrcode
    if (printType === 'qrcode') {
      console.log('print qrcode');
    }
    // print barcode
    if (printType === 'barcode') {
      console.log('print barcode');
    }
  }

  render() {
    const { info, loading } = this.props;
    const { id } = this.props.match.params;
    if (loading || !info) {
      return (
        <PageHeaderLayout title="基础详情页">
          <Card bordered={false}>
            加载中...
            <Spin />
          </Card>
        </PageHeaderLayout>
      );
    }

    if (info.err) {
      return (
        <PageHeaderLayout title="基础详情页">
          <Card bordered={false}>
            获取详情出现错误：{info.err.message}
            <Spin />
          </Card>
        </PageHeaderLayout>
      );
    }
    const curAsset = info.asset;
    const assetAttr = curAsset.asset_attr;
    const attrColumns = [];
    if (typeof assetAttr === 'object') {
      for (const attr in assetAttr) {
        if (assetAttr[attr]) {
          attrColumns.push({
            title: attr,
            dataIndex: attr,
            key: attr,
          });
        }
      }
    }
    const qrInfo = {
      value: `${curAsset.asset_name}:${id}`,
      size: 300,
      bgcolor: '#fff',
      fgcolor: '#222',
      level: 'H',
    };
    return (
      <PageHeaderLayout title="基础详情页">
        <Card bordered={false}>
          <DescriptionList size="large" title="用户信息" style={{ marginBottom: 32 }}>
            <Description term="用户姓名">{info.login_name}</Description>
            <Description term="联系电话">{info.mobile_phone}</Description>
            <Description term="备注">{info.asset_desc}</Description>
          </DescriptionList>
          <Divider style={{ marginBottom: 32 }} />
          <div className={styles.title}>资产信息</div>
          <Table
            style={{ marginBottom: 24 }}
            pagination={false}
            loading={loading}
            dataSource={[assetAttr]}
            columns={attrColumns}
            rowKey={(record, index) => index}
          />
          <div className={styles.title}>服务信息（暂无）</div>
          <Table
            style={{ marginBottom: 16 }}
            pagination={false}
            loading={loading}
            dataSource={[]}
            columns={progressColumns}
            rowKey={(record, index) => index}
          />
        </Card>
        <Card bordered={false} style={{ marginTop: 32 }}>
          <DescriptionList size="large" title="条码信息" style={{ marginBottom: 32, height: 500 }}>
            <Row>
              <Col span="8">
                <Card
                  title="二维码"
                  col="6"
                  extra={<Button type="primary" data-type="qrcode" onClick={this.saveCanvas}>打印</Button>}
                  style={{ width: 400, height: 400 }}
                >
                  <QRCode {...qrInfo} />
                </Card>
              </Col>
              <Col span="8">
                <Card
                  title="条形码"
                  col="6"
                  extra={<Button type="primary" data-type="barcode" onClick={this.saveCanvas}>打印</Button>}
                  style={{ width: 400, height: 200 }}
                >
                  <canvas className="bar-code" ref={(c) => { this.barcode = c; }} />
                </Card>
              </Col>
            </Row>
          </DescriptionList>
        </Card>
      </PageHeaderLayout>
    );
  }
}
